package com.atguigu.gmall.scheduled.cart;


import com.atguigu.gmall.scheduled.mapper.CartMapper;
import com.atguigu.gmall.scheduled.pojo.Cart;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

//同步redis数据到mysql
@Component
public class CartJobHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CartMapper cartMapper;

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final String EXCEPTION_KEY = "cart:exception";

    private static final String KEY_PREFIX = "cart:info:";
    @XxlJob("syncCartData")
    public ReturnT<String> syncCartData(String param){
        // 获取redis出现异常的userId
        BoundSetOperations<String, String> setOps = redisTemplate.boundSetOps(EXCEPTION_KEY);
        String userId = setOps.pop();
        //判断userId是否为空
         while (StringUtils.isNotBlank(userId)) {

             //删除mysql中的该用户的信息
             cartMapper.delete(new UpdateWrapper<Cart>().eq("user_id",userId));

            //查询redis中该用户的购物车
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
            //获取该用户的购物车字符串集合
            List<Object> cartJsons = hashOps.values();


            if (CollectionUtils.isEmpty(cartJsons)){
                userId = setOps.pop();
                //继续循环
                continue;
            }
             //遍历将每条购物车字符串转化为购物车对象同步到mysql
             cartJsons.forEach(cartJson->{
                 try {
                     Cart cart = MAPPER.readValue(cartJson.toString(), Cart.class);
                     //将数据同步到mysql
                     cartMapper.insert(cart);
                 } catch (JsonProcessingException e) {
                     e.printStackTrace();
                 }
             });
            //获取下一个用户
             userId = setOps.pop();
        }
        return ReturnT.SUCCESS;
    }
}
